package servlet;

import java.io.IOException;
import java.sql.Date;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.OrderDao;
import dao.OrderItemDao;
import dao.ProductDao;
import dao.Factoty.DaoFactory;
import domain.Address;
import domain.Order;
import domain.Product;
import domain.User;
import service.Factory.ServiceFactory;

/**
 * Servlet implementation class PurchaseServlet
 */
@WebServlet("/PurchaseServlet")
public class PurchaseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PurchaseServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    /**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String from = request.getParameter("from");
		List<Product> products = new ArrayList<Product>();
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute("_user");
		
		if (user == null) {
			response.sendRedirect(request.getContextPath()+ "/client/login.jsp");
			return;
		}
		
		if (from.equals("product")) {
			String id = request.getParameter("pid");
			int select = Integer.parseInt(request.getParameter("select"));
			Product product;
			try {
				product = ServiceFactory.getProductServiceInstance().findProductById(id);
				product.setSelct(select);
				products.add(product);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				response.sendRedirect(request.getContextPath()+ "/HomeServlet");
				return;
			}
		} else if (from.equals("shoppingCart")) {
			products = (List<Product>) session.getAttribute("shoppingCart");
		} else {
			response.sendRedirect(request.getContextPath()+ "/HomeServlet");
			return;
		}
		
		double amount = 0.0d;
		
		for (int i = 0; i < products.size(); i++) {
			amount += products.get(i).getSelect() * products.get(i).getPrice();
		}
 		
		session.setAttribute("purchase", products);
		
		try {
			request.setAttribute("products", products);
			request.setAttribute("amount", amount);
			request.setAttribute("addresses", ServiceFactory.getAddressServiceInstance().findAddressByUser(user.getId(), 1, 1000));
			request.getRequestDispatcher("/client/Purchase.jsp").forward(request, response);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response.sendRedirect(request.getContextPath()+ "/HomeServlet");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute("_user");
		String addressId = request.getParameter("address");
		
		if (user == null || addressId == null) {
			response.sendRedirect(request.getContextPath()+ "/client/purchasefail.jsp");
			return;
		}
		
		List<Product> purchase = (List<Product>) session.getAttribute("purchase");
		
		if (purchase.size() > 0) {
			try {
				User curUser = (User) session.getAttribute("_user");
				double amount = 0;
				
				for (int i = 0; i < purchase.size(); i++) {
					amount += purchase.get(i).getSelect() * purchase.get(i).getPrice();
				}
				
				Order order = new Order();
				Address address = ServiceFactory.getAddressServiceInstance().findAddressById(Integer.parseInt(addressId));
				
				order.setId(UUID.randomUUID().toString());
				order.setMoney(amount);
				order.setReceiverAddress(address.getAddress());
				order.setReceiverName(address.getName());
				order.setReceiverPhone(address.getTelephone());
				order.setPaystate(1);
				order.setOrdertime(new Date(System.currentTimeMillis()));
				order.setUser(curUser);
				ServiceFactory.getOrderServiceInstance().createOrder(order);
				
				for (int i = 0; i < purchase.size(); i++) {
					try {
						ServiceFactory.getOrderItemServiceInstance().createOrderItem(order, purchase.get(i), purchase.get(i).getSelect());

						purchase.get(i).setPnum(purchase.get(i).getPnum() - purchase.get(i).getSelect());
						ServiceFactory.getProductServiceInstance().updatePnumOfProduct(purchase.get(i));
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						response.sendRedirect(request.getContextPath()+ "/client/purchasefail.jsp");
						return;
					}
				}
				
				session.removeAttribute("purchase");
				session.removeAttribute("shoppingCart");
				response.sendRedirect(request.getContextPath()+ "/client/purchasesuccess.jsp");
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				response.sendRedirect(request.getContextPath()+ "/client/purchasefail.jsp");
				return;
			}
		} else {
			response.sendRedirect(request.getContextPath()+ "/client/purchasefail.jsp");
		}
	}

}
